package com.dong.appdemo;

import android.content.ComponentName;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.pingplusplus.android.PaymentActivity;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Locale;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private EditText editText;
    private Button button;
    private String currentAmount = "";
    private static String YOUR_URL ="http://218.244.151.190/demo/charge";
    public static final String URL = YOUR_URL;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        editText = (EditText) findViewById(R.id.et);

        button = (Button) findViewById(R.id.btn);

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            //当输入金额改变后，调用该方法，格式化金额
            @Override
            public void afterTextChanged(Editable s) {
                if (!s.toString().equals(currentAmount)) {
                    editText.removeTextChangedListener(this);
                    String replaceable = String.format("[%s, \\s.]", NumberFormat.getCurrencyInstance(Locale.CHINA).getCurrency().getSymbol(Locale.CHINA));
                    String cleanString = s.toString().replaceAll(replaceable, "");

                    if (cleanString.equals("") || new BigDecimal(cleanString).toString().equals("0")) {
                        editText.setText(null);
                    } else {
                        double parsed = Double.parseDouble(cleanString);
                        String formatted = NumberFormat.getCurrencyInstance(Locale.CHINA).format((parsed / 100));
                        currentAmount = formatted;
                        editText.setText(formatted);
                        editText.setSelection(formatted.length());
                    }
                    editText.addTextChangedListener(this);
                }
            }
        });


        button.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        String amountText = editText.getText().toString();
        if(TextUtils.isEmpty(amountText)) return;

        String replaceable = String.format("[%s, \\s.]", NumberFormat.getCurrencyInstance(Locale.CHINA).getCurrency().getSymbol(Locale.CHINA));
        String cleanString = amountText.toString().replaceAll(replaceable, "");
        int amount = Integer.valueOf(new BigDecimal(cleanString).toString());

        if(v.getId() == R.id.btn){
            //输入哪种方式支付，如：alipay，支付金额
            new PaymentTask().execute(new PaymentRequest("alipay",amount));
        }
    }

    class PaymentTask extends AsyncTask<PaymentRequest, Void, String>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            button.setOnClickListener(null);
        }

        @Override
        protected String doInBackground(PaymentRequest... params) {
            String data = null;
            String json = new Gson().toJson(params[0]);
            try {
                data = postJson(URL,json);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return data;
        }

        @Override
        protected void onPostExecute(String data) {
            super.onPostExecute(data);

            /*Intent intent = new Intent();
            String packageName = getPackageName();
            //ComponentName componentName = new ComponentName(packageName, packageName + ".wxapi.WXPayEntryActivity");
            ComponentName componentName = new ComponentName(packageName, "com.pingplusplus.android.PaymentActivity");
            intent.setComponent(componentName);*/

            Intent intent = new Intent(MainActivity.this,PaymentActivity.class);
            intent.putExtra(PaymentActivity.EXTRA_CHARGE, data);
            startActivityForResult(intent, 1);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 1){
            String result = data.getExtras().getString("pay_result");
            if("success".equals(result)){
                Toast.makeText(this,"付款成功",Toast.LENGTH_SHORT).show();
            }
        }
    }

    private static String postJson(String url,String json) throws IOException {
        MediaType type = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(type, json);
        Request request = new Request.Builder().url(url).post(body).build();

        OkHttpClient client = new OkHttpClient();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }


    class PaymentRequest{
        String channel;
        int amount;

        public PaymentRequest(String channel, int amount){
            this.channel = channel;
            this.amount = amount;
        }
    }
}
